import OfflineData from '/common/offline-data-cache.js'
import checkUpdate from '@/uni_modules/uni-upgrade-center-app/utils/check-update'
const url = 'ws://localhost:48080/infra/ws?token=4ce64ffd488e473fa5842417a854a28b'

export const connect = () => {
	
	const savedScreenId = uni.getStorageSync('screenId');
	const client = uni.connectSocket({
		url,
		header: {
			'Tenant-Id': '1',
			'content-type': 'application/json'
		}
	});
	uni.onSocketOpen(function(res) {
		console.log('WebSocket连接已打开！');
	});
	uni.onSocketMessage(function(res) {
		// {"type":"demo-message-receive","content":"{\"fromUserId\":1,\"text\":\"456\",\"single\":false}"}
		// { "topic": "screen:command","screenId": "1130","command": "updateOfflineData"}

		console.log('收到服务器内容：' + res.data);

		try {
			const json = JSON.parse(res.data)
			const text = JSON.parse(json.content).text
			// {command:'', params: {}}
			const msg = JSON.parse(text)
			if (msg.topic==='screen:command' && savedScreenId == msg.screenId){
				execCommand(msg.command, msg.params)
			}
		} catch (e) {
			console.error(e)
		}
	});
	// client.on('reconnect', () => {
	// 	console.log('Reconnecting...')
	// })
	// client.on('error', function(error) {
	// 	console.log(error)
	// })
	// client.on('connect', function() {
	// 	console.log('Connected')
	// 	uni.showToast({
	// 		title:'MQTT已连接'
	// 	})
	// 	// 订阅主题
	// 	client.subscribe(['ym/command'], function(err) {
	// 		if (!err) {
	// 			// 发布消息
	// 			client.publish('ym/screen', JSON.stringify({
	// 					screenId: savedScreenId,
	// 					status: 'online',
	// 					msg: '上线了'
	// 				}), {
	// 					qos: 0,
	// 					retain: false
	// 				},
	// 				(e) => {
	// 					console.log(e)
	// 				}
	// 			)
	// 		}
	// 	})
	// })
	// // 接收消息
	// client.on('message', function(topic, payload) {
	// 	// message is Buffer
	// 	console.log(topic, payload.toString())
	// 	if (topic === 'ym/command') {
	// 		try {
	// 			// {command:'', params: {}}
	// 			const msg = JSON.parse(payload)
	// 			execCommand(msg.command, msg.params)
	// 		} catch (e) {
	// 			console.error(e)
	// 		}
	// 	}
	// })


	return null;

}

// 根据不同命令执行不同的方法
const execCommand = async (command, params) => {
	switch (command) {
		case 'restart':
			// 重启
			console.log('重启')
			plus.runtime.restart();
			return;
		case 'updateOfflineData':
			// 更新离线数据
			console.log('更新离线数据')
			const savedScreenId = uni.getStorageSync('screenId');
			await OfflineData.updateOfflineData(savedScreenId)
			// 页面重载
			const pages = getCurrentPages()
			// 声明一个pages使用getCurrentPages方法
			const curPage = pages[pages.length - 1]
			uni.redirectTo({
				url: '/' + curPage.route
			})
			break;
		case 'clearCache':
			// 清除除了ID外的所有缓存
			const storage = uni.getStorageInfoSync();
			console.log(storage);
			storage.keys.forEach(key => {
				if (key !== 'screenId') {
					uni.removeStorageSync(key);
				}
			})
			uni.redirectTo({
				url: '/pages/Login/Login'
			})
			break;
		case 'clearAllCache':
			// 清除所有缓存
			uni.clearStorageSync();
			uni.redirectTo({
				url: '/pages/Login/Login'
			})
			break;
		case 'updateApp':
			// 更新版本
			await checkUpdate();
			break;

	}
}